package com.demo.fork.demo1;

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : YU.TAN
 * @date : 2021/8/11 18:32
 *
 * TheKingRecursiveSumTask中定义了任务计算的起止范围（sumBegin和sumEnd）和拆分阈值（threshold），以及核心计算逻辑compute()
 */
public class TheKingRecursiveSumTask extends RecursiveTask<Long> {

    private static final AtomicInteger taskCount = new AtomicInteger();
    private final int sumBegin;
    private final int sumEnd;
    /**
     * 任务拆分阈值，当任务尺寸大于该值时，进行拆分
     */
    private final int threshold;

    public TheKingRecursiveSumTask(int sumBegin, int sumEnd, int threshold) {
        this.sumBegin = sumBegin;
        this.sumEnd = sumEnd;
        this.threshold = threshold;
    }

    @Override
    protected Long compute() {
        if ((sumEnd - sumBegin) > threshold) {
            //两个书之间的差值大于阈值，拆分任务
            TheKingRecursiveSumTask taskA = new TheKingRecursiveSumTask(sumBegin, (sumBegin + sumEnd) / 2, threshold);
            TheKingRecursiveSumTask taskB = new TheKingRecursiveSumTask((sumBegin + sumEnd) / 2, sumEnd, threshold);
            taskA.fork();
            taskB.fork();
            taskCount.incrementAndGet();
            return taskA.join() + taskB.join();
        }

        //直接执行结果
        long result = 0L;
        for (int i = sumBegin; i < sumEnd; i++) {
            result += i;
        }
        return result;
    }

    public static AtomicInteger getTaskCount() {
        return taskCount;
    }

}
